package BlockingQueueInstance;

class MyBlockingQueue {
    private String[] elems = null;
    private int rear = 0;
    private int front = 0;
    private int size = 0;

    Object locker = new Object();
    public MyBlockingQueue (int capacity) {
        elems = new String[capacity];
    }

    public void put(String elem) {
        synchronized (locker) {
            while (size >= elems.length) {
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            elems[rear] = elem;
            rear++;
            if (rear >= elems.length) {
                rear = 0;
            }
            size++;
            locker.notify();
        }
    }

    public String take() {
        String ret = null;
        synchronized (locker) {
            while (size == 0) {
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            ret = elems[front];
            front++;
            if (front >= elems.length) {
                front = 0;
            }
            size--;
            locker.notify();
        }
        return ret;
    }
}

public class BlockingQueue {
    public static void main(String[] args) {

        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000);
        Thread t1 = new Thread(() -> {
            int n = 0;
            while(true) {
                System.out.println("create "+n);
                myBlockingQueue.put("AAA");
                n++;
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("consumed "+myBlockingQueue.take());
            }
        });

        t1.start();
        t2.start();
    }
}
